package com.itheima.Service.impl;

import com.itheima.Mapper.AddressMapper;
import com.itheima.Service.AddressService;
import com.itheima.pojo.Address;

import com.itheima.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 获取当前登录用户ID（从ThreadLocal中获取，由拦截器填充）
     */
    private Integer getCurrentUserId() {
        System.out.println(BaseContext.getCurrentId());
        return BaseContext.getCurrentId();

    }

    @Override
    public List<Address> list() {
        // 查询当前用户的所有地址
        return addressMapper.list(getCurrentUserId());
    }

    @Override
    public Address getDefault() {
        // 查询当前用户的默认地址
        Address defaultAddress = addressMapper.findDefault(getCurrentUserId());
        // 如果没有默认地址，返回第一个地址
        if (defaultAddress == null) {
            List<Address> addressList = addressMapper.list(getCurrentUserId());
            return addressList.isEmpty() ? null : addressList.get(0);
        }
        return defaultAddress;
    }

    @Override
    public Address get(Integer id) {
        // 查询地址并校验归属（防止越权访问）
        Address address = addressMapper.get(id);
        if (address == null || !address.getUserId().equals(getCurrentUserId())) {
            throw new RuntimeException("地址不存在或无权访问");
        }
        return address;
    }

    @Override
    @Transactional
    public void add(Address address) {
        // 补全用户ID和时间信息
        address.setUserId(getCurrentUserId());
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());

        // 如果设置为默认地址，先取消其他地址的默认状态
        if (address.getIsDefault() == 1) {
            addressMapper.cancelDefault(getCurrentUserId());
        } else {
            // 如果是第一个地址，自动设为默认
            Integer count = addressMapper.count(getCurrentUserId());
            if (count == 0) {
                address.setIsDefault(1);
            }
        }
        //更新完整地址
        address.setFullAddress(address.getProvince()+address.getCity()+address.getDistrict()+address.getDetailAddress());

        // 保存地址
        addressMapper.insert(address);
    }

    @Override
    @Transactional
    public void update(Address address) {
        // 校验地址归属
        Address oldAddress = addressMapper.get(address.getId());
        if (oldAddress == null || !oldAddress.getUserId().equals(getCurrentUserId())) {
            throw new RuntimeException("地址不存在或无权访问");
        }

        // 补全信息
        address.setUserId(getCurrentUserId());
        address.setUpdateTime(LocalDateTime.now());

        // 如果设置为默认地址，先取消其他地址的默认状态
        if (address.getIsDefault() == 1) {
            addressMapper.cancelDefault(getCurrentUserId());
        }

        //更新完整地址
        address.setFullAddress(address.getProvince()+address.getCity()+address.getDistrict()+address.getDetailAddress());

        // 更新地址
        addressMapper.update(address);
    }

    @Override
    @Transactional
    public void setDefault(Integer id) {
        // 校验地址归属
        Address address = addressMapper.get(id);
        if (address == null || !address.getUserId().equals(getCurrentUserId())) {
            throw new RuntimeException("地址不存在或无权访问");
        }

        // 先取消其他地址的默认状态
        addressMapper.cancelDefault(getCurrentUserId());
        // 设置当前地址为默认
        addressMapper.setDefault(id);
    }

    @Override
    public void delete(Integer id) {
        // 校验地址归属
        Address address = addressMapper.get(id);
        if (address == null || !address.getUserId().equals(getCurrentUserId())) {
            throw new RuntimeException("地址不存在或无权访问");
        }

        // 删除地址
        addressMapper.delete(id);
    }
}